package com.infocollect.project.api.ui;


import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.infocollect.common.utils.ServletUtils;
import com.infocollect.common.utils.StringUtils;
import com.infocollect.common.utils.poi.ExcelCustomUtil;
import com.infocollect.framework.security.LoginUser;
import com.infocollect.framework.security.service.TokenService;
import com.infocollect.project.api.entity.TappFromEntity;
import com.infocollect.project.api.enums.FromTypeEnum;
import com.infocollect.project.api.helper.MapHelper;
import com.infocollect.project.api.req.ConfigQueryJsonReq;
import com.infocollect.project.api.req.FromSaveInfoReq;
import com.infocollect.project.api.service.ApiCommService;
import com.infocollect.project.api.service.ITappFromService;
import com.infocollect.project.api.service.ITappFromTempService;
import com.infocollect.project.api.service.impl.QuestionnaireServiceImpl;
import com.infocollect.project.api.vo.AuditOperatorVo;
import com.infocollect.project.api.vo.AuditReportVo;
import com.infocollect.project.api.vo.FromTempContextVO;
import com.infocollect.project.form.vo.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.infocollect.project.grant.domain.QuestionAuditProcess;
import com.infocollect.project.grant.service.IQuestionAuditProcessService;
import io.swagger.annotations.Api;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * (TappFrom)表控制层
 *
 * @author makejava
 * @since 2019-12-25 10:32:29
 */
@Api(value = "From", tags = "表单模板信息")
@RestController
@RequestMapping("From")
public class TappFromController {
    private static final Logger log = LoggerFactory.getLogger(TappFromController.class);
    @Autowired
    private TokenService tokenService;
    /**
     * 服务对象
     */
    @Resource
    private ITappFromService tappFromService;
    /**
     * 服务对象
     */
    @Resource
    private ITappFromTempService tappFromTempService;
    @Autowired
    private QuestionnaireServiceImpl questionnaireService;
    @Autowired
    private ApiCommService apiCommService;
    @Autowired
    private IQuestionAuditProcessService auditProcessService;
    /**
     * 通过主键查询单条数据
     *
     * @param
     * @return 单条数据
     */
    @PostMapping("getFromInfo")
    @ResponseBody
    public R<TappFromEntity> selectOne(@RequestParam("fromId") Long fromId) throws IOException {
        return R.newOk(this.tappFromService.queryById(fromId));
    }

    /**
     * 保存表单信息
     *
     * @param
     * @return
     * @throws IOException
     */
    @PostMapping("saveData")
    @ResponseBody
    public  R<Long> SaveData(@RequestBody FromSaveInfoReq param) throws IOException {
        try {
            TappFromEntity entity = this.tappFromService.queryById(param.getId());
//            CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
            LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
            FromTypeEnum fromtype=FromTypeEnum.ELEMENT;
            switch (param.getDesignType()){
                case "/buildquestionnaire.html":fromtype=FromTypeEnum.QUESTIONNAIRE; break;
                case "/buildpublish.html":fromtype=FromTypeEnum.ELEMENT;; break;
                case "/buildpublishAntDesign.html":fromtype=FromTypeEnum.ANTDESIGN; break;
                case "/buildscreenanalyse.html":fromtype=FromTypeEnum.SCREENANALYSE; break;
                case "/buildFlowFrom.html":fromtype=FromTypeEnum.FLOWFROM; break;
                default:break;
            }
            if (entity == null) {
                entity = new TappFromEntity();
                entity.setFid(IdWorker.getId());
                entity.setFcreateby(currentUserInfo.getUsername());
                entity.setFlastupdateby(currentUserInfo.getUsername());
                entity.setFcreationdate(new Date());
                entity.setFlastupdatedate(new Date());
                entity.setFremarks(param.getFremarks());
                entity.setFromcontent(param.getFromcontent());
                entity.setFromdesignjson(param.getFromdesignjson());
                entity.setFromtype(fromtype);
                entity.setFromname(param.getFromName());
                entity.setFromTableName(param.getFromTableName());
                entity.setDialogwidth(param.getDialogwidth());
                entity.setEndDate(param.getEndDate());
                entity.setStartDate(param.getStartDate());
                entity.setIsInput(param.getIsInput());
                entity.setIsModify(param.getIsModify());
                entity.setIsWhite(param.getIsWhite());
                entity.setModifyEndDate(param.getModifyEndDate());
                entity.setShowEndDate(param.getShowEndDate());
                entity.setIsNetconfirm(param.getIsNetconfirm());
                entity = this.tappFromService.insert(entity);
            }
            else {
                entity.setFlastupdateby(currentUserInfo.getUsername());
                entity.setFlastupdatedate(new Date());
                entity.setFremarks(param.getFremarks());
                entity.setFromcontent(param.getFromcontent());
                entity.setFromdesignjson(param.getFromdesignjson());
                entity.setFromname(param.getFromName());
                entity.setFromtype(fromtype);
                entity.setFromTableName(param.getFromTableName());
                entity.setDialogwidth(param.getDialogwidth());
                entity.setEndDate(param.getEndDate());
                entity.setStartDate(param.getStartDate());
                entity.setIsInput(param.getIsInput());
                entity.setIsModify(param.getIsModify());
                entity.setIsWhite(param.getIsWhite());
                entity.setModifyEndDate(param.getModifyEndDate());
                entity.setShowEndDate(param.getShowEndDate());
                entity.setIsNetconfirm(param.getIsNetconfirm());
                entity = this.tappFromService.update(entity);
            }
            if(!FromTypeEnum.SCREENANALYSE.equals(fromtype)){
                questionnaireService.TableEidt(param.getFromdesignjson(),param.getFromTableName());
            }
            return R.newOk(entity.getFid());
        } catch (Exception ex) {
            ex.printStackTrace();
         return    R.newError("保存报错！具体错误信息为：" + ex);
        }
    }

    /**
     * 获取表单模板
     *
     * @return
     */
    @PostMapping("getFromDesignJson")
    @ResponseBody
    public R<String> GetFromDesignJson(@RequestParam("fromId") Long fromId) throws IOException {
        return R.newOk( tappFromService.GetFromDesignJson(fromId));
    }

    @PostMapping("getFromTempContext")
    @ResponseBody
    public  R<FromTempContextVO>  GetFromTempContext(@RequestParam("fromId") Long fromId) throws IOException {
        TappFromEntity tappFrom= this.tappFromService.queryById(fromId);
        if(tappFrom==null){
            return R.newError("找不到模板页！");
        }
        FromTempContextVO resut=new FromTempContextVO();
        resut.setFromtempcontext(tappFrom.getFromcontent());
        resut.setFromid(tappFrom.getFid());
        resut.setFromname(tappFrom.getFromname());
        return R.newOk( resut);
    }

    /**
     * 查询流程列表
     *
     * @param param post过来的参数
     * @return 单条数据
     */
    @PostMapping("queryPageList")
    public R< List<TappFromEntity>> queryPageList(@RequestBody Map<String, String> param) throws Exception {
        R< List<TappFromEntity>> result=new R();
        TappFromEntity tappFrom = new TappFromEntity();
        MapHelper.setObjectValue(tappFrom, param);
        int page = Integer.parseInt(param.get("page"));
        int rows = Integer.parseInt(param.get("rows"));
        PageHelper.startPage(page, rows);
        List<TappFromEntity> list = tappFromService.querypageList(tappFrom);
        PageInfo pageInfo = new PageInfo(list);
        return R.newOk(list,(int)pageInfo.getTotal());

    }

    /**
     * 查询流程列表
     *
     * @param param post过来的参数
     * @return 单条数据
     */
    @PostMapping("queryall")
    @ResponseBody
    public R< List<TappFromEntity>> queryAll(@RequestBody TappFromEntity param){
        return R.newOk(tappFromService.queryAll(param));
    }


    /**
     * 保存设置查询条件
     * @return
     */
    @PostMapping("saveConfigQueryJson")
    public  R<String> saveConfigQueryJson(@RequestBody ConfigQueryJsonReq param){
        Boolean isSave=   tappFromService.saveConfigQueryJson(param);
        if(isSave){
            return R.newOk("保存成功！");
        }
        return R.newError("保存失败");
    }

    /**
     * 获取查询条件的配置
     * @param fid
     * @return
     */
    @PostMapping("getConfigQueryJson")
    public  R<String>  getConfigQueryJson(Long fid){
       return R.newOk(tappFromService.getConfigQueryJson(fid));
    }
    /**
     * @author dongpj
     * @date 2022/5/1 19:40
     * @param
     * @return
     * @describe 下载数据导入模版
     */
    @PostMapping(value=  "importTemplate/{ApiCode}", produces = "application/json;charset=UTF-8")
    public R<String> importTemplate(@RequestBody JSONObject param, @PathVariable("ApiCode") String ApiCode, HttpServletRequest req, HttpServletResponse response) throws Exception{
        return apiCommService.ExportExlceTemplate(param, ApiCode, response, req);
    }
    /**
     * @author dongpj
     * @date 2022/5/1 21:24
     * @param
     * @return
     * @describe 导入具体项目数据
     */
    @PostMapping("importData")
    public R<String>  importData(MultipartFile file, boolean updateSupport, Long formId,HttpServletRequest req) throws Exception{
        ExcelCustomUtil util = new ExcelCustomUtil();
        List<Map<String,Object>> importDataList= util.importExcel(file.getInputStream());
        List<JSONObject> importJSONObjectList =  tappFromService.getImportData(importDataList,formId,updateSupport);
        //apiCommService.apiComm(param, ApiCode, req);
        TappFromEntity tappFromEntity =  tappFromService.queryById(formId);
        String tableName = tappFromEntity.getFromTableName();
        String apiCode = tableName+".SaveDataInfo";
        log.error(importJSONObjectList.toString());
        importJSONObjectList.stream().forEach(param->{
            try {
                param.put("auditflag","未填报");
                R<Object> result = apiCommService.apiComm(param, apiCode, req);
                log.error(result.getMsg());
            }catch(Exception ex){

            }
        });
        return R.newOk();
    }
    /**
     * @author dongpj
     * @date 2022/5/2 18:12
     * @param
     * @return
     * @describe 审核操作，通过或不通过都调用这里。
     */
    @PostMapping("auditOperator")
    public R<String> auditOperator(@RequestBody JSONObject param){
        LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
        if(StringUtils.isEmpty(currentUserInfo.getUsername())){
            R<String> r = new R<String>("获取审核人信息失败");
            r.setCode(-2);
            return r;
        }
        TappFromEntity tappForm = tappFromService.queryById(param.getLong("formid"));

        if(tappForm==null)
        {
            R<String> r = new R<String>("获取项目信息失败");
            r.setCode(-2);
            return r;
        }

        AuditOperatorVo audit = new AuditOperatorVo();
        if("是".equals(tappForm.getIsNetconfirm()))
        {
            if("审核通过".equals(param.getString("auditflag")))
            {
                audit.setAuditflag("待确认");
            }else
            {
                audit.setAuditflag(param.getString("auditflag"));
            }
        }
        else
        {
          audit.setAuditflag(param.getString("auditflag"));
        }

        audit.setAuditremark(param.get("auditremark")==null?"":param.getString("auditremark"));
        audit.setFormId(param.getLong("formid"));
        audit.setTableNewId(param.getString("$tableNewId"));
        audit.setTableName(param.getString("questionName"));
        audit.setAuditby(String.valueOf(currentUserInfo.getUserId()));
        audit.setAuditbyname(currentUserInfo.getUsername());
        tappFromService.auditOperator(audit);
//        return tappFromService.getNextAuditData(String.valueOf(currentUserInfo.getUserId()),audit.getTableName());
        return tappFromService.lockAuditData(String.valueOf(currentUserInfo.getUserId()),currentUserInfo.getUsername(),audit.getTableName());
    }
    /**
     * @author dongpj
     * @date 2022/8/27 10:19
     * @param param
     * @return com.infocollect.project.form.vo.R<java.lang.String>
     * @describe 随机提取1条记录，更新到当前用户下面，并返回数据id，如果当用户下面还有记录，直接返回
     */
    @PostMapping("extractAuditData")
    public R<String> extractAuditData(@RequestBody JSONObject param){
        //1、先判断本人名下必须是没有记录了。
        //2、从数据库随机获取10条记录
        String fromTableName = param.getString("fromTableName");
        LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
        return tappFromService.lockAuditData(String.valueOf(currentUserInfo.getUserId()),currentUserInfo.getUsername(),fromTableName);
    }
    @PostMapping("lockRecord")
    public R<String> lockRecord(@RequestBody JSONObject param){
        //1、先判断本人名下必须是没有记录了。
        //2、从数据库随机获取10条记录
//        String fromTableName = param.getString("fromTableName");
        LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
        return tappFromService.lockRecord(String.valueOf(currentUserInfo.getUserId()),currentUserInfo.getUsername(),param);
    }
    /**
     * @author dongpj
     * @date 2022/8/27 10:45
     * @param
     * @return com.infocollect.project.form.vo.R<java.lang.String>
     * @describe 释放本人已提取的数据
     */
    @PostMapping("unExtractSelfAuditData")
    public R<String> unExtractSelfAuditData(@RequestBody JSONObject param){
        String fromTableName = param.getString("fromTableName");
        LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
        return tappFromService.unExtractAuditData(String.valueOf(currentUserInfo.getUserId()),currentUserInfo.getUsername(),fromTableName);
    }
    /**
     * @author dongpj
     * @date 2022/8/27 10:55
     * @param param
     * @return com.infocollect.project.form.vo.R<java.lang.String>
     * @describe 释放指定记录
     */
    @PostMapping("unExtractFidAuditData")
    public R<String> unExtractFidAuditData(@RequestBody JSONObject param){
        String fromTableName = param.getString("fromTableName");
        String fid = param.getString("fid");
        return tappFromService.unExtractFidAuditData(fromTableName,fid);
    }
    @PostMapping("getAuditprocessByFid")
    public R<List<QuestionAuditProcess>> getAuditprocessByFid(@RequestBody JSONObject param){
        if(StringUtils.isEmpty(param.getString("$tableNewId"))){
            return R.newOk(new ArrayList<QuestionAuditProcess>());
        }
        LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
        QuestionAuditProcess auditProcess = new QuestionAuditProcess();
        auditProcess.setFid(Long.valueOf(param.getString("$tableNewId")));
        auditProcess.setTablename(param.getString("questionName"));
//        auditProcess.setAuditby(String.valueOf(currentUserInfo.getUserId()));
        List<QuestionAuditProcess> auditProcessesLis= auditProcessService.selectQuestionAuditProcessList(auditProcess);
        return R.newOk(auditProcessesLis);
    }

    @PostMapping("getAuditReport")
    public R<List<AuditReportVo>> getAuditReport(@RequestBody JSONObject param){
        return apiCommService.getAuditReport(param.getString("fromTableName"));
    }

}
